package com.jlsoft.lakala;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Base64;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lkl.cloudpos.mdx.aidl.AidlDeviceService;
import com.lkl.cloudpos.mdx.aidl.printer.AidlPrinter;
import com.lkl.cloudpos.mdx.aidl.printer.PrintItemObj;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * 拉卡拉打印插件
 */
public class PrinterPlugin extends CordovaPlugin {

    public static final String LKL_SERVICE_ACTION = "lkl_cloudpos_mdx_service";

    private AidlDeviceService serviceManager;
    private AidlPrinter printerDev = null;

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        bindService();
    }

    //设别服务连接桥
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder serviceBinder) {
            if (serviceBinder != null) {    //绑定成功
                AidlDeviceService sm = AidlDeviceService.Stub.asInterface(serviceBinder);
                serviceManager = sm;
                try {
                    printerDev = AidlPrinter.Stub.asInterface(serviceManager.getPrinter());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("aaa", "AidlService服务断开了");
        }
    };

    //绑定服务
    public void bindService() {
        Context context = this.cordova.getContext();
        try {
            Intent intent = new Intent();
            intent.setAction(LKL_SERVICE_ACTION);
            Intent eintent = new Intent(getExplicitIntent(context, intent));
            Log.d("packageName", eintent.toString());
            boolean flag = context.bindService(eintent, conn, Context.BIND_AUTO_CREATE);
            if (flag) {
                Log.d("aaa", "服务绑定成功");
            } else {
                Log.d("aaa", "服务绑定失败");
            }
        } catch (Exception e) {
            return;
        }

    }

    public static Intent getExplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryIntentServices(implicitIntent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            //得到手机上已经安装的应用的名字,即在AndriodMainfest.xml中的app_name。
            String appName = resolveInfo.loadLabel(pm).toString();
            //得到应用所在包的名字,即在AndriodMainfest.xml中的package的值。
            String packageName = resolveInfo.serviceInfo.packageName;
        }
        // Make sure only one match was found
        if (resolveInfos == null || resolveInfos.size() != 1) {
            return null;
        }
        ResolveInfo serviceInfo = resolveInfos.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;

        ComponentName component = new ComponentName(packageName, className);
        Intent explicitIntent = new Intent(implicitIntent);
        explicitIntent.setComponent(component);
        return explicitIntent;
    }

    @Override
    public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException {
        if (serviceManager == null) return false;

        if ("print".equals(action)) {
            return paresPrinter(rawArgs);
        }

        return true;
    }

    private boolean paresPrinter(String args) {
        JSONArray ja = Json.toJA(args);

        for (Object o : ja) {
            JSONObject printer = Json.toJO(o);

            try {
                if ("img".equals(printer.getString("type"))) {
                    String mp_logo_base64 = printer.getString("text");
                    byte[] imgBytes = Base64.decode(mp_logo_base64.split(",")[1], Base64.DEFAULT);
                    Bitmap imgs = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);
                    printerDev.printBmp(0, printer.getInteger("w"), printer.getInteger("h"), imgs, null);
                } else {
                    PrintItemObj obj = paresPrintObj(printer);
                    List<PrintItemObj> printItemObjs = new ArrayList<>();
                    printItemObjs.add(obj);
                    printerDev.printText(printItemObjs, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return true;
    }

    private PrintItemObj paresPrintObj(JSONObject jo) {
        PrintItemObj obj = new PrintItemObj(jo.getString("text"));

        if (jo.containsKey("size"))
            obj.setFontSize(jo.getInteger("size"));

        if (jo.containsKey("align")) {
            switch (jo.getString("align")) {
                case "center":
                    obj.setAlign(PrintItemObj.ALIGN.CENTER);
                    break;
                case "right":
                    obj.setAlign(PrintItemObj.ALIGN.RIGHT);
                    break;
            }
        }

        if (jo.containsKey("isBold"))
            obj.setBold(jo.getBoolean("isBold"));

        return obj;
    }
}
